import miniLoading from '@/components/MiniLoading'
import { DirectiveBinding } from 'vue'

const loadingDirective = () => {
  let loadingElementMain: HTMLDivElement | null = null
  let removeLoading = () => {}
  return {
    mounted(el: HTMLImageElement) {
      el.style.position = 'relative'
      const loadingElement = document.createElement('div')

      loadingElement.style.top = '0px'
      loadingElement.style.left = '0px'
      loadingElement.style.bottom = '0px'
      loadingElement.style.right = '0px'
      loadingElement.style.position = 'absolute'
      loadingElement.style.zIndex = '-1'
      // const { width, height } = el.getBoundingClientRect()
      // loadingElement.style.width = '100%'
      // loadingElement.style.height = '100%'

      el.appendChild(loadingElement)
      loadingElementMain = loadingElement
    },
    updated(el: HTMLImageElement, bind: DirectiveBinding) {
      const loading = bind.value
      removeLoading()
      if (loading) {
        removeLoading = miniLoading(loading, loadingElementMain!)
        loadingElementMain!.style.zIndex = '99'
      } else {
        removeLoading && removeLoading()
        removeLoading = () => {}
        loadingElementMain!.style.zIndex = '-1'
      }

      // @ts-ignore
      // const resizeObserver = new ResizeObserver((enties) => {
      //   enties.forEach(() => {
      //     if (loadingElement.parentElement === el) {
      //       removeLoading && removeLoading()
      //     }
      //     const { width, height } = el.getBoundingClientRect()
      //     loadingElement.style.width = width + 'px'
      //     loadingElement.style.height = height + 'px'
      //     removeLoading = miniLoading(loading, loadingElement)
      //     el.appendChild(loadingElement)
      //   })
      // })
      // resizeObserver.observe(el)
    },
    unmounted() {
      console.log('unmounted')
    }
  }
}
export default loadingDirective()
